﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CameraPrpject
{
    public class Camera
    {
        // Methods
        public Camera(IntPtr handle, int width, int height)
        {
            this.mControlPtr = handle;
            this.mWidth = width;
            this.mHeight = height;
        }
        private bool capDriverConnect(IntPtr lwnd, short i)
        {
            return Video.SendMessage(lwnd, 0x40a, i, 0);
        }

        private bool capDriverDisconnect(IntPtr lwnd)
        {
            return Video.SendMessage(lwnd, 0x40b, (short)0, 0);
        }

        private bool capPreview(IntPtr lwnd, bool f)
        {
            return Video.SendMessage(lwnd, 0x432, f, 0);
        }

        private bool capPreviewRate(IntPtr lwnd, short wMS)
        {
            return Video.SendMessage(lwnd, 0x434, wMS, 0);
        }
        private bool MapPreviewRate(IntPtr lwnd)
        {
            return Video.SendMessage(lwnd, 0x41e, 0, 0);
        }

        private bool capSetVideoFormat(IntPtr hCapWnd, ref Video.BITMAPINFO BmpFormat, int CapFormatSize)
        {
            return Video.SendMessage(hCapWnd, 0x42d, CapFormatSize, ref BmpFormat);
        }
        // Video.SendMessage(this.hHwnd, 0x41e, 0, 0);
        public void CloseWebcam()
        {
            this.capDriverDisconnect(this.lwndC);
        }
        public void StartWebCam()
        {
            byte[] buffer1 = new byte[100];
            byte[] buffer2 = new byte[100];
            Video.capGetDriverDescriptionA(0, buffer1, 100, buffer2, 100);
            this.lwndC = Video.capCreateCaptureWindowA(buffer1, 1342177280, 0, 0, this.mWidth, this.mHeight, this.mControlPtr, 0);
            if (this.capDriverConnect(this.lwndC, 0))
            {
                Video.BITMAPINFO bitmapinfo1;
                this.capPreviewRate(this.lwndC, 0x42);
                this.capPreview(this.lwndC, true);
                bitmapinfo1 = new Video.BITMAPINFO();
                bitmapinfo1.bmiHeader.biSize = Video.SizeOf(bitmapinfo1.bmiHeader);
                bitmapinfo1.bmiHeader.biWidth = 320;
                bitmapinfo1.bmiHeader.biHeight = 240;
                bitmapinfo1.bmiHeader.biPlanes = 1;
                bitmapinfo1.bmiHeader.biBitCount = 0x18;
                this.capSetVideoFormat(this.lwndC, ref bitmapinfo1, Video.SizeOf(bitmapinfo1));
                Video.SetWindowPos(this.lwndC, 0, 0, 0, this.mWidth, this.mHeight, 6);
            }
        }
        // Fields
        public IntPtr lwndC;
        private IntPtr mControlPtr;
        private int mHeight;
        private int mWidth;
    }
}

